package cn.gcjxsc.payment.controller;

import cn.gcjxsc.common.consts.PayStatus;
import cn.gcjxsc.common.data.wx.QueryOrder;
import cn.gcjxsc.payment.data.WeChatConfig;
import cn.gcjxsc.payment.data.pay.PayData;
import cn.gcjxsc.payment.data.wx.order.CreateOrder;
import cn.gcjxsc.payment.entity.wx.PayRecord;
import cn.gcjxsc.payment.service.wx.PayRecordService;
import cn.gcjxsc.payment.service.wx.WeChatApiService;
import cn.gcjxsc.payment.util.WxUtil;
import com.zgxl.common.util.AjaxResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author pumbaa
 * @since 1.0
 */
@RestController("apiWxPaymentController")
@RequestMapping("/api/wx")
public class PaymentController{
    private Logger logger = LoggerFactory.getLogger(PaymentController.class);
    @Autowired
    private WeChatConfig weChatConfig;
    @Autowired
    private WeChatApiService apiService;
    @Autowired
    private PayRecordService payRecordService;

    /**
     * 查询订单支付状态
     * @param tradeNo 交易号
     * @param type 类型.1=系统交易号,其他=微信流水号
     * @return
     */
    @RequestMapping("/queryPay")
    public String queryOrderPayStatusAction(@RequestParam("tradeNo") String tradeNo,
                                            @RequestParam(value = "type", defaultValue = "1", required = false) int type) {
        QueryOrder.QueryOrderResponse response;
        if (type == 1) {
            response = apiService.queryOrder(weChatConfig, tradeNo);
        } else {
            response = apiService.queryOrderByTransactionId(weChatConfig, tradeNo);
        }
        if (null == response) {
            return WxUtil.FAIL;
        } else {
            if (response.getReturn_code().equals(WxUtil.SUCCESS) && response.getResult_code().equals(WxUtil.SUCCESS)) {
                return response.getTrade_state();
            } else {
                return WxUtil.FAIL;
            }
        }
    }

    /**
     * 微信支付统一下单
     * @param payData 支付数据
     * @return 成功返回微信预支付交易号,失败返回提示信息.
     */
    @RequestMapping("/unifiedOrder")
    public AjaxResponse unifiedOrder(@Validated PayData payData, BindingResult bindingResult){
        if (bindingResult.getErrorCount() > 0) {
            return AjaxResponse.ajaxFailure(bindingResult.getFieldError().getDefaultMessage());
        }
        //生成支付记录.
        PayRecord payRecord = payRecordService.findBySn(payData.getSn());
        if (null == payRecord) {
            payRecord = payRecordService.newPayRecord(payData, weChatConfig);
        }
        if (payRecord.getStatus() == PayStatus.PAID.ordinal()) {
            return AjaxResponse.ajaxFailure("交易已完成,请勿重复操作");
        }
        try {
            payRecordService.saveOrUpdate(payRecord);
        } catch (Exception e) {
            logger.error("保存微信支付记录失败.{}, {}", payData.getSn(), e.getMessage());
            return AjaxResponse.ajaxFailure("操作失败,请稍后再试");
        }
        payData.setSn(payRecord.getTradeNo());
        CreateOrder.Response response = apiService.createPayOrder(weChatConfig, payData);
        if (response.getReturn_code().equalsIgnoreCase(WxUtil.SUCCESS)) {
            if (response.getResult_code().equalsIgnoreCase(WxUtil.SUCCESS)) {
                return AjaxResponse.ajaxSuccess("", response.getPrepay_id());
            }
            return AjaxResponse.ajaxFailure(response.getErr_code_des());
        }
        return AjaxResponse.ajaxFailure(response.getReturn_msg());
    }
}
